<?php

namespace app\enterprise\controller;

use app\enterprise\model\course\Courseware;
use app\enterprise\model\course\Course;
use app\enterprise\model\plan\Plan as PlanModel;
use app\enterprise\model\plan\PlanCourse;
use app\enterprise\model\plan\PlanStaff;
use app\enterprise\model\plan\Staff;
use app\enterprise\model\User as UserModel;
use app\enterprise\model\plan\Snap as SnapModel;
use app\enterprise\model\plan\StaffExam;
use app\enterprise\model\TrainType as TrainTypeModel;
use app\enterprise\service\DataType;
use app\enterprise\model\Project;
use app\Request;
use think\exception\ValidateException;
use think\facade\Db;
use app\services\face\CertService;
use app\enterprise\model\course\Teacher;
use app\enterprise\model\department\Department as DepartmentModel;

class Plan extends Enterprise
{

    public function list()
    {

        $page = input('page', 1);
        $size = input('size', 10);
        $plan_name = input('plan_name', '');
        $type_ids = input('type_ids', []);
        $code = input('code', '');
        $time_status = input('time_status', '');
        $online_status = input('online_status', '');
        $start_time = strtotime(input('start_time', ''));
        $end_time = strtotime(input('end_time', ''));
        $userIds = userIds($this->adminId);
        $where = [];

        $where[] = ['creator_id', 'in', $userIds];
        $where[] = ['status', '=', 1];

        $data = PlanModel::when($plan_name, function ($query) use ($plan_name) {
            $query->where('plan_name', 'like', '%' . $plan_name . '%');
        })

            ->when($code, function ($query) use ($code) {
                $query->where('code', 'like', '%' . $code . '%');
            })
            ->when($time_status, function ($query) use ($time_status) {
                $query->where('time_status', $time_status);
            })
            ->where(function ($query) use ($type_ids) {
                if (!empty($type_ids)) {
                    foreach ($type_ids as $typeId) {
                        $query->whereOr('type_ids', 'like', '%,' . $typeId . ',%');
                    }
                }
            })
            ->when($online_status, function ($query) use ($online_status) {
                $query->where('online_status', $online_status);
            })
            ->where($start_time, function ($query) use ($start_time) {
                $query->where('create_time', '>=', $start_time);
            })
            ->when($end_time, function ($query) use ($end_time) {
                $query->where('create_time', '<=', $end_time);
            })
            ->where($where)
            ->with('user')
            ->order('id', 'desc')
            ->paginate($size)
            ->each(function ($item) {
                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids'] ?? '');
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item->type_name = implode(',', $types);
                }
                $item->start_time = date('Y-m-d', $item->start_time);
                $item->end_time = date('Y-m-d', $item->end_time);
                if ($item->plan_type == 2 && $item->project_id) {
                    $project = Project::getOne($item->project_id);
                    $item->project_name = $project['project_name'];
                } else {
                    $item->project_name = '';
                }

                if (!empty($item->user)) {
                    $item->company_name = $item->user->company_name;
                    unset($item->user);
                } else {
                    $item->company_name = '未知';
                }
            });

        //上线消息通知
        app(\app\enterprise\controller\PushService::class)->sendCultivateOnline('标题', '内容');

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total(),
            'total_page' => $data->lastPage(),
        ]);
    }

    /**
     * 保存
     * @return void
     */
    public function save()
    {
        $id = input('id', '');

        $data = $this->request->only([
            'plan_name',
            'type_ids',
            'code',
            'start_time',
            'end_time',
            'exam_status',
            'exam_id',
            'online_status',
            'remarks',
            'course_ids',
            'staff_ids',
            'plan_type',
            'project_id',
            'interval_time',
            'snap_count',
            'courseware_snap_count'
        ]);



        try {
            validate([
                'type_ids|培训类型' => 'require|array',
                'plan_name|培训名称' => 'require|max:255',
                'code|编号' => 'require|max:255',
                'start_time|培训开始时间' => 'require',
                'end_time|培训结束时间' => 'require',
                'exam_status|是否考试' => 'require|in:1,2',
                'remarks|备注' => 'max:255',
                'course_ids|课程' => 'array',
                'staff_ids|人员' => 'array',
                'exam_id|试卷' => 'requireIf:exam_status,1|number',
                'plan_type|培训类型' => 'require|in:1,2',
                // 'project_id|项目'=>'requireIf:plan_type,2|number',
                'interval_time|抓拍时间' => 'require|number',
                'snap_count|抓拍总次数' => 'require|number',
                'courseware_snap_count|课件抓拍' => 'require|number',
            ])->check($data);
        } catch (ValidateException $e) {
            return app('json')->fail($e->getError());
        }

        if ($data['plan_type'] == 1) {
            $data['project_id'] = 0;
        }

        // 将department_ids转为数组
        $data['type_ids'] = ',' . implode(',', $data['type_ids']) . ',';

        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);

        // 结束时间不能早于开始时间
        if ($data['start_time'] >= $data['end_time']) {
            return app('json')->fail('开始时间不能早于结束时间');
        }


        if ($data['exam_status'] == 2) {
            $data['exam_id'] = 0;
        }

        Db::startTrans();
        try {
            if (!$id) {
                // 新增培训
                $data['company_id'] = $this->adminInfo['company_id'];
                // 创建人id
                $data['creator_id'] = $this->adminId;
                $res = PlanModel::create($data);
                $id = $res->id;
            } else {
                $plan = PlanModel::getOne($id);
                if (!$plan) {
                    return app('json')->fail('培训不存在');
                }
                if ($plan->company_id != $this->adminId) {
                    return app('json')->fail('您没有权限修改该培训');
                }
                if ($plan->online_status != 1) {
                    return app('json')->fail('该状态下的培训不能修改');
                }
                PlanModel::update($data, ['id' => $id]);
                PlanCourse::arrayDelete(['plan_id' => $id]);
            }

            $course_ids = array_unique(input('course_ids', []));
            if ($course_ids) {
                $course_data = [];
                foreach ($course_ids as $course_id) {
                    $course_data[] = [
                        'plan_id' => $id,
                        'course_id' => $course_id,
                        'create_time' => time(),
                    ];
                }
                PlanCourse::insertAll($course_data);
            }
            $staff_ids = array_unique(input('staff_ids', []));
            if ($staff_ids) {
                $exist_staff_ids = PlanStaff::where(['plan_id' => $id, 'status' => 1])->column('staff_id');

                // 要新增的数据
                $insert_ids = array_diff($staff_ids, $exist_staff_ids);
                if ($insert_ids) {
                    foreach ($insert_ids as $staff_id) {
                        $plan_staff = [
                            'plan_id' => $id,
                            'staff_id' => $staff_id,
                            'status' => 1,
                            'company_id' => $this->adminInfo['company_id'],
                        ];
                        PlanStaff::create($plan_staff);
                    }
                }
                // 要删除的数据
                $del_ids = array_diff($exist_staff_ids, $staff_ids);

                if ($del_ids) {
                    // 删除staff_id在$del_ids数组中的数据
                    PlanStaff::arrayDelete(['plan_id' => $id, 'staff_id' => $del_ids]);
                }
            } else {
                PlanStaff::arrayDelete(['plan_id' => $id]);
            }
            Db::commit();
            return app('json')->success();
        } catch (\Exception $e) {
            Db::rollback();
            return app('json')->fail($e->getMessage());
        }
    }


    public function info()
    {
        $id = input('id', '');
        $data = PlanModel::getOne($id);
        if (!$data) {
            return app('json')->fail('培训不存在');
        }

        try {
            $trainTypeRelates = DataType::getTrainTypeRelates($data['type_ids']);
            $data['selected_type_ids'] = $trainTypeRelates['id_chains'];

            $data['type_names'] =  '-';
            if (!empty($trainTypeRelates['title_chains'])) {
                $data['type_names'] = implode('/', array_map(function ($item) {
                    return implode('-', $item);
                }, $trainTypeRelates['title_chains']));
            }


            $data['type_ids'] = explode(',', trim($data['type_ids'], ','));
        } catch (\Exception $e) {
            $data['type_ids'] = [];
        }

        $data['start_time'] = date('Y-m-d H:i:s', $data->start_time);
        $data['end_time'] = date('Y-m-d H:i:s', $data->end_time);


        $types = DataType::getTrainType();

        $course_ids = PlanCourse::where('plan_id', $id)->where('status', 1)->column('course_id');


        $staff_ids = PlanStaff::where('plan_id', $id)->where('status', 1)->column('staff_id');

        return app('json')->success([
            'data' => $data,
            'types' => $types,
            'course_ids' => $course_ids,
            'staff_ids' => $staff_ids,
        ]);
    }

    public function courses()
    {

        $id = input('id', '');

        $page = input('page', 1);
        $size = input('size', '');
        $course_name = input('course_name', '');
        $type_ids = input('type_ids', []);


        $courses = [];
        $data = ['total' => 0, 'total_page' => 0];
        $query = PlanCourse::hasWhere('course', function ($q) use ($course_name, $type_ids) {
            $q->where('status', 1);
            if ($course_name) {
                $q->where('course_name', 'like', '%' . $course_name . '%');
            }
            if (!empty($type_ids)) {
                $q->where(function ($subQuery) use ($type_ids) {
                    foreach ($type_ids as $type_id) {
                        $subQuery->whereOr('type_ids', 'like', '%,' . $type_id . ',%');
                    }
                });
            }
        })->where(['PlanCourse.status' => 1, 'plan_id' => $id]);

        if ($size) {
            $result = $query->paginate($size);
            $data['total'] = $result->total();
            $data['total_page'] = $result->lastPage();
        } else {
            $result = $query->select();
        }
        $result->each(function ($item) use (&$courses) {
            $course = [];
            //            $course['id'] = $item->id;
            $course['id'] = $item->course_id;
            $course['course_name'] = $item->course->course_name;
            $course['course_id'] = $item->course_id;
            $course['create_time'] = $item->create_time;


            $course['process'] = '0.00';
            // 上课学院数
            $course['staff_study_count'] = 0;
            // 完成学员数
            $course['staff_complete_count'] = 0;
            $course['total_video_duration'] = 0;

            if ($item->course->type_ids) {
                $typeIds = explode(',', $item->course->type_ids ?? '');
                $types = TrainTypeModel::whereIn('id', $typeIds)
                    ->column('title');
                $course['type_name'] = implode(',', $types);
            } else {
                $course['type_name'] = '';
            }

            $ware_ids = json_decode($item->course->ware_json);
            if (empty($ware_ids)) {
                $course['ware_count'] = 0;
                $course['ware_duration'] = 0;
                $course['ware_hour'] = 0;
            } else {

                $statistics = Courseware::whereIn('id',  $ware_ids)
                    ->field('count(*) as ware_total_count, sum(duration) as ware_total_duration, sum(hour) as ware_total_hour')
                    ->find();
                $course['ware_count'] = $statistics['ware_total_count'];
                $course['ware_duration'] = $statistics['ware_total_duration'];
                $course['ware_hour'] = $statistics['ware_total_hour'];
            }
            $courses[] = $course;
        });
        $data['list'] = $courses;
        $data['ids'] = PlanCourse::where(['plan_id' => $id, 'status' => 1])->column('course_id');
        return app('json')->success($data);
    }

    public function staffs()
    {
        $id = input('id', '');
        if (!$id) {
            return app('json')->fail('参数错误');
        }
        $page = input('page', 1);
        $size = input('size', '');

        $username = input('username', '');
        $idcard = input('idcard', '');
        $mobile = input('mobile', '');
        $complete_status = input('complete_status', '');

        $where = [
            'PlanStaff.status'  => 1,
            'plan_id'           => $id
        ];

        $exam_status = input('exam_status', ''); //考试
        $exam_ret = input('exam_ret', ''); // 合格

        if (!empty($exam_status)) {
            $where['exam_status'] = $exam_status;
        }
        if (!empty($exam_ret)) {
            $where['exam_ret'] = $exam_ret;
        }


        $query = PlanStaff::hasWhere('staff', function ($q) use ($username, $idcard, $mobile) {

            $q->where('status', 1);

            if ($username) {
                $q->where('username', 'like', '%' . $username . '%');
            }
            if ($idcard) {
                $q->where('idcard', 'like', '%' . $idcard . '%');
            }
            if ($mobile) {
                $q->where('mobile', 'like', '%' . $mobile . '%');
            }
        })->where($where)
            ->when($complete_status, function ($q) use ($complete_status) {
                $q->where('complete_status', $complete_status);
            })->order('id', 'asc');

        $staffs = [];

        if ($size) {
            $result = $query->paginate($size);
            $data['total'] = $result->total();
            $data['total_page'] = $result->lastPage();
        } else {
            $result = $query->select();
        }

        $departments = DepartmentModel::where('status', 1)->select()->toArray();


        $user_info = UserModel::where('id', $this->adminId)->with('department')->find()->toArray();
        $statistics = [
            'participate_count'             =>  0, // 参加人员总数
            'completed_count'               =>  0, // 学习完成人数
            'uncompleted_count'             =>  0, // 学习未完成人数
            'exam_participate_count'        =>  0, // 参加考试人数
            'exam_not_participate_count'    =>  0, // 未参加考试人数
            'exam_pass_count'               =>  0, // 考试合格人数
            'exam_fail_count'               =>  0, // 考试不合格人数
        ];
        $result->each(function ($item) use (&$staffs, $user_info, &$statistics, $departments) {
            $staff = [];
            $staff['id'] = $item->staff_id;
            $staff['plan_staff_id'] = $item->id;
            $staff['username'] = $item->staff->username;
            $staff['idcard'] =  idCardMask($item->staff->idcard);
            $staff['mobile'] = $item->staff->mobile;
            $staff['study_status'] = $item->study_status;
            $staff['auth_status'] = 0;
            $staff['total_ware_count'] = 0;
            $staff['complete_ware_count'] = 0;
            $staff['complete_status'] = $item->complete_status; // 学习状态

            if ($item->complete_status == 1) {
                $staff['complete_status_text'] = '学习中';
            } else if ($item->complete_status == 9) {
                $staff['complete_status_text'] = '待签字';
            } else {
                $staff['complete_status_text'] = '已完成';
            }

            $s = StaffExam::getOne($item->staff_exam_id);
            if ($s) {
                $staff['exam_ret'] = $s['exam_ret'];
            } else {
                $staff['exam_ret'] = '';
            }
            $staff['exam_ret'] = $item->exam_ret;
            $staff['exam_point'] = $item->exam_point ?? '';

            $staff['complete_img_url'] = $item->complete_img_url;

            // 进度
            $staff['progress'] = $item->progress . '%';
            // 组织架构
            if (!empty($user_info['department']['department_name'])) {
                $staff['department_name'] = $user_info['department']['department_name'];
            } else {
                $staff['department_name'] = '';
            }

            // 1:未考试，2：考试中，9：考试结束 exam_status
            if ($item->exam_status == 1) {
                $staff['exam_status_text'] = '未考试';
            } else if ($item->exam_status == 2) {
                $staff['exam_status_text'] = '考试中';
            } else {
                $staff['exam_status_text'] = '考试结束';
            }
            $staff['sex'] = $item->staff->sex;

            $staff['department_path'] = getCategoryPath($departments, $item->staff->department_id);;

            $staffs[] = $staff;

            // 统计
            $statistics['participate_count'] += 1;

            if ($item->complete_status == 1) {
                // 学习未完成
                $statistics['uncompleted_count'] += 1;
            } else {
                // 学习已完成
                $statistics['completed_count'] += 1;
            }

            //            if ($item->exam_status == 1) {
            //                // 未考试
            //                $statistics['exam_not_participate_count'] += 1;
            //            } else {
            //                // 已考试
            //                $statistics['exam_participate_count'] += 1;
            //            }
            // 合格 跟 不合格都算已考试的
            if ($item->exam_ret == 8) {
                // 不合格
                $statistics['exam_fail_count'] += 1;
                // 已考试
                $statistics['exam_participate_count'] += 1;
            } else if ($item->exam_ret == 9) {
                // 合格
                $statistics['exam_pass_count'] += 1;
                // 已考试
                $statistics['exam_participate_count'] += 1;
            } else {
                // 未考试
                $statistics['exam_not_participate_count'] += 1;
            }
        });

        $data['list'] = $staffs;
        $data['ids'] = PlanStaff::where('plan_id', $id)->where('status', 1)->column('staff_id');
        $data['statistics'] = $statistics;
        return app('json')->success($data);
    }
    //抓拍列表
    public function staffsSnap()
    {
        $id = input('id', '');
        $plan_staff_id = input('plan_staff_id', '');
        if (!$id || !$plan_staff_id) {
            return app('json')->fail('参数错误');
        }
        $page = input('page', 1);
        $size = input('size', '');

        $username = '';
        $idcard = '';
        $mobile = '';
        $study_status = '';

        $query = SnapModel::where(['plan_id' => $plan_staff_id, 'staff_id' => $id])
            ->order('id', 'asc');

        $staffs = [];

        if ($size) {
            $result = $query->paginate($size);
            $data['total'] = $result->total();
            $data['total_page'] = $result->lastPage();
        } else {
            $result = $query->select();
        }
        $username = Staff::where('id', $id)->value('username');
        $planID = PlanStaff::where('id', $plan_staff_id)->value('plan_id');
        $plan_name = PlanModel::where('id', $planID)->value('plan_name');
        //        echo $username;exit;
        $result->each(function ($item) use (&$staffs) {

            $staff = [];
            $staff['id'] = $item->id;
            $staff['plan_id'] = $item->plan_id;
            $staff['staff_id'] = $item->staff_id;
            $staff['create_time'] = $item->create_time;
            $staff['img_url'] = $item->img_url;
            $staffs[] = $staff;
        });
        foreach ($staffs as $k => $val) {
            $staffs[$k]['username']  = $username;
            $staffs[$k]['plan_name']  = $plan_name;
        }
        $data['list'] = $staffs;
        $data['ids'] = PlanStaff::where('plan_id', $id)->where('status', 1)->column('staff_id');
        return app('json')->success($data);
    }


    public function staffsSnapList()
    {
        $id = input('id', '');
        $plan_staff_id = input('plan_staff_id', '');
        if (!$id || !$plan_staff_id) {
            return app('json')->fail('参数错误');
        }
        $size = input('size', '');

        // 培训id
        $plan_staff = PlanStaff::where('id', $plan_staff_id)->find();
        $planID = $plan_staff->plan_id;

        $query = SnapModel::where(['plan_id' => $planID, 'staff_id' => $id, 'status' => 1])
            ->order('id', 'asc');

        $staffs = [];

        $result = $query->paginate($size);
        $data['total'] = $result->total();
        $data['total_page'] = $result->lastPage();
        // 人员信息
        $username = Staff::where('id', $id)->value('username');

        // 培训名
        $plan_name = PlanModel::where('id', $planID)->value('plan_name');
        if ($plan_staff->complete_status == 1) {
            $complete_status_text = '学习中';
        } else if ($plan_staff->complete_status == 9) {
            $complete_status_text = '待签字';
        } else {
            $complete_status_text = '已完成';
        }

        if ($plan_staff->exam_status == 1) {
            $exam_statuss_text = '未考试';
        } else if ($plan_staff->exam_status == 2) {
            $exam_statuss_text = '考试中';
        } else {
            $exam_statuss_text = '考试结束';
        }

        $user_info = [
            'username'              => $username,
            'id'                    => $id,
            'plan_name'             => $plan_name,
            'plan_id'               => $planID,
            'progress'              => $plan_staff->progress, // 进度
            'complete_status'       => $plan_staff->complete_status, // 学习状态, 1:学习中 9:代签字 10:已完成
            'complete_status_text'  => $complete_status_text,
            'exam_status'           => $plan_staff->exam_status, // 考试状态  1:未考试 2:考试中 9:考试结束
            'exam_status_text'      => $exam_statuss_text,
            'complete_img_status'   => $plan_staff->complete_img_status == 1 ? '未生成' : '已生成', // 结业证书是否生成
            'complete_img_url'      => $plan_staff->complete_img_url, // 结业证图片
            'code'                  => $plan_staff->code, // 证书编码
            'study_start_time'        => empty($plan_staff->study_start_time) ? '' : date('Y-m-d H:i:s', $plan_staff->study_start_time), // 开始时间
            'study_end_time'        => empty($plan_staff->study_end_time) ? '' : date('Y-m-d H:i:s', $plan_staff->study_end_time), // 完成时间
            'sign_img_url'          => $plan_staff->sign_img_url, // 签字图片
            'sign_time'             => empty($plan_staff->sign_time) ? '' : date('Y-m-d H:i:s', $plan_staff->sign_time), // 签字时间
        ];
        $result->each(function ($item) use (&$staffs) {

            $staff = [];
            $staff['id'] = $item->id;
            $staff['plan_id'] = $item->plan_id;
            $staff['staff_id'] = $item->staff_id;
            $staff['create_time'] = $item->create_time;
            $staff['img_url'] = $item->img_url;
            $staff['ret'] = $item->ret;
            $staff['status'] = $item->status;
            $staff['courseware_id'] = $item->courseware_id;
            $staff['sel_status'] = $item->sel_status;
            $staff['is_sel_status'] = $item->sel_status == 1 ? true : false;
            $staff['type'] = $item->type;
            if ($item->type == 1) {
                $staff['type_text'] = '学习课件';
            } else if ($item->type == 2) {
                $staff['type_text'] = '考试';
            } else {
                $staff['type_text'] = '交底';
            }

            $staffs[] = $staff;
        });

        $data['list'] = $staffs;
        $data['userInfo'] = $user_info;
        return app('json')->success($data);
    }

    public function delStudentSnap()
    {
        $id = input('id', ''); // 抓拍id
        $staff_id = input('staff_id', ''); // 学员id

        if (!$id || !$staff_id) {
            return app('json')->fail('参数错误');
        }
        $planStaff = Staff::getOne($staff_id);

        if (!$planStaff) {
            return app('json')->fail('学员不存在');
        }

        if ($planStaff['company_id'] != $this->adminId) {
            return app('json')->fail('无此权限');
        }

        SnapModel::dataDelete($id);

        return app('json')->success('操作成功');
    }

    public function uploadImageInfo()
    {
        $staff_id = input('staff_id', ''); // 学员id
        $plan_id = input('plan_id', ''); // 培训计划id
        $url = input('url', ''); // 培训计划id
        if (!$plan_id || !$staff_id || !$url) {
            return app('json')->fail('参数错误');
        }
        $parent = [
            'staff_id'      => $staff_id,
            'plan_id'       => $plan_id,
            'img_url'       => $url,
            'method'        => 1,
            'type'          => 1,
            'ret'           => 1,
            'create_time'   =>  time(),
            'update_time'   =>  time(),
        ];
        SnapModel::insert($parent);
        return app('json')->success('上传成功');
    }

    public function cartlist()
    {
        $id = input('id', '');

        if (empty($id)) {
            return app('json')->fail('参数错误');
        }
        $plan_staff = PlanStaff::where(['plan_id' => $id, 'status' => 1])->with('staff')->select()->toArray();

        $data = [];
        foreach ($plan_staff as $key => $value) {

            if (!empty($value['staff'])) {
                $username = $value['staff']['username'];
                $idcard = $value['staff']['idcard'];
                unset($value['staff']);
            } else {
                $username = '';
                $idcard = '';
            }
            $data[] = [
                'complete_img_url'  => $value['complete_img_url'],
                'username'          => $username,
                'idcard'            => $idcard,
            ];
        }

        return app('json')->success($data);
    }

    public function addStaff()
    {
        $id = input('id', '');
        if (!$id) {
            return app('json')->fail('参数错误');
        }

        $staff_ids = input('staff_ids', []);
        if (empty($staff_ids)) {
            return app('json')->fail('请选择学员');
        }

        $plan = PlanModel::getOne($id);
        if (!$plan) {
            return app('json')->fail('培训不存在');
        }
        if ($plan['company_id'] != $this->adminId) {
            return app('json')->fail('无权限进行此操作');
        }
        if ($plan['online_status'] != 1) {
            return app('json')->fail('培训不是草稿状态, 不可添加学员');
        }

        $exist_staff_ids = PlanStaff::where(['plan_id' => $id, 'status' => 1])->column('staff_id');

        foreach ($staff_ids as $staff_id) {
            if (!in_array($staff_id, (array)$exist_staff_ids)) {
                $plan_staff = [
                    'plan_id' => $id,
                    'staff_id' => $staff_id,
                    'status' => 1,
                    'company_id' => $this->adminId,
                ];
                PlanStaff::create($plan_staff);
            }
        }

        return app('json')->success('操作成功');
    }

    public function nullify()
    {
        $id = input('id', '');

        $plan = PlanModel::getOne($id);

        if (!$plan) {
            return app('json')->fail('培训不存在');
        }

        //        if ($plan['company_id'] != $this->adminId) {
        //            return app('json')->fail('无权限进行此操作');
        //        }
        if ($plan['status'] == 2) {
            return app('json')->fail('此培训已作废，请勿重复操作');
        }

        PlanModel::update(['online_status' => 2], ['id' => $id]);

        return app('json')->success('操作成功');
    }

    public function online()
    {
        $id = input('id', '');

        if (!$id) {
            return app('json')->fail('参数错误');
        }

        $plan = PlanModel::getOne($id);

        if (!$plan) {
            return app('json')->fail('培训不存在');
        }

        //        if ($plan['company_id'] != $this->adminId) {
        //            return app('json')->fail('无权限进行此操作');
        //        }
        if ($plan['status'] == 2) {
            return app('json')->fail('此培训已作废，请勿重复操作');
        }

        // 判断是否添加课程
        if (!PlanCourse::where(['plan_id' => $id, 'status' => 1])->find()) {
            return app('json')->fail('请先添加课程');
        }

        if (!PlanStaff::where(['plan_id' => $id, 'status' => 1])->find()) {
            return app('json')->fail('请先添加人员');
        }

        PlanModel::update(['online_status' => 9], ['id' => $id]);

        return app('json')->success();
    }

    public function removeStaff()
    {
        $id = input('id', '');

        if (!$id) {
            return app('json')->fail('参数错误');
        }
        $planStaff = PlanStaff::getOne($id);

        if (!$planStaff) {
            return app('json')->fail('学员不存在');
        }

        if ($planStaff['company_id'] != $this->adminId) {
            return app('json')->fail('无此权限');
        }

        PlanStaff::dataDelete($id);

        return app('json')->success('操作成功');
    }

    public function copy()
    {
        $id = input('id', '');

        if (!$id) {
            return app('json')->fail('参数错误');
        }

        $plan = PlanModel::getOne($id);

        if (!$plan) {
            return app('json')->fail('培训不存在');
        }

        $plan = $plan->toArray();

        unset($plan['id']);
        $plan['status'] = 1;
        $plan['online_status'] = 1;
        $plan['company_id'] = $this->adminId;
        $plan['create_time'] = time();
        unset($plan['update_time']);
        $plan['plan_name'] = $plan['plan_name'] . '副本';
        $plan['code'] = $plan['code'] . '副本';
        $res = PlanModel::create($plan);

        // 查询课程
        $course_ids = PlanCourse::where('plan_id', $id)->where('status', 1)->column('course_id');

        if (!empty($course_ids)) {
            $plan_courses = [];
            foreach ($course_ids as $course_id) {
                $plan_course = [
                    'plan_id' => $res['id'],
                    'course_id' => $course_id,
                    'status' => 1,
                    'create_time' => time(),
                ];
                $plan_courses[] = $plan_course;
            }
            PlanCourse::insertAll($plan_courses);
        }

        // 查询人员
        $staffs = PlanStaff::where('plan_id', $id)->where('status', 1)->select()->toArray();

        if (!empty($staffs)) {
            $plan_staffs = [];
            foreach ($staffs as $staff) {
                $plan_staff = [
                    'plan_id' => $res['id'],
                    'staff_id' => $staff['staff_id'],
                    'status' => 1,
                    'create_time' => time(),
                    'company_id' => $this->adminId,
                ];
                $plan_staffs[] = $plan_staff;
            }
            PlanStaff::insertAll($plan_staffs);
        }

        return app('json')->success('操作成功');
    }

    public function selStatusChange()
    {
        $id = input('id', '');
        $sel_status = input('sel_status', '');

        if (empty($id) || empty($sel_status)) {
            return app('json')->fail('缺少参数');
        }

        SnapModel::update(['sel_status' => $sel_status], ['id' => $id]);
        return app('json')->success('切换成功');
    }

    public function generateCert()
    {
        $plan_id = input('plan_id', '');
        $staff_id = input('staff_id', '');
        $service = new CertService();
        $ret = $service->jieye($plan_id, $staff_id, 1);
        if ($ret == true) {
            return app('json')->success(['url' => $service->getImageUrl()]);
        }
        return app('json')->fail($service->getError());
    }

    public function statistics()
    {

        //        $data = [
        //            'participate_count'             =>  0, // 参加人员总数
        //            'completed_count'               =>  0, // 学习完成人数
        //            'uncompleted_count'             =>  0, // 学习未完成人数
        //            'exam_participate_count'        =>  0, // 参加考试人数
        //            'exam_pass_count'               =>  0, // 考试合格人数
        //            'exam_fail_count'               =>  0, // 考试不合格人数
        //            'exam_not_participate_count'    =>  0, // 未参加考试人数
        //        ];

        $plan_id = input('id', '');
        if (empty($plan_id)) {
            return app('json')->fail('缺少参数');
        }
        //        $plan_staff = PlanStaff::where(['plan_id' => $plan_id, 'status' => 1])->with('staff')->select()->toArray();
        $plan_staff = PlanStaff::where(['plan_id' => $plan_id, 'status' => 1])->select()->toArray();
        $data = [
            'participate_count'             =>  count($plan_staff) ?? 0, // 参加人员总数
            'completed_count'               =>  0, // 学习完成人数
            'uncompleted_count'             =>  0, // 学习未完成人数
            'exam_participate_count'        =>  0, // 参加考试人数
            'exam_not_participate_count'    =>  0, // 未参加考试人数
            'exam_pass_count'               =>  0, // 考试合格人数
            'exam_fail_count'               =>  0, // 考试不合格人数
        ];

        if (!empty($plan_staff)) {
            foreach ($plan_staff as $key => $value) {
                if ($value['complete_status'] == 1) {
                    // 学习未完成
                    $data['uncompleted_count'] += 1;
                } else {
                    // 学习已完成
                    $data['completed_count'] += 1;
                }

                if ($value['exam_status'] == 1) {
                    // 未考试
                    $data['exam_not_participate_count'] += 1;
                } else {
                    // 已考试
                    $data['exam_participate_count'] += 1;
                }

                if ($value['exam_ret'] == 8) {
                    // 不合格
                    $data['exam_fail_count'] += 1;
                } else if ($value['exam_ret'] == 9) {
                    // 合格
                    $data['exam_pass_count'] += 1;
                }
            }
        }
        return app('json')->success($data);
    }

    public function getCourseware()
    {
        $course_id = input('course_id', '');
        if (empty($course_id)) {
            return app('json')->fail('参数有误');
        }

        $course_ware_json = Course::where('id', $course_id)->value('ware_json');

        if (!empty($course_ware_json)) {
            $ids = json_decode($course_ware_json, true);
            $coursewares = Courseware::whereIn('id', $ids)->with('teacher')->select()->toArray();
            foreach ($coursewares as $key => &$value) {
                if (!empty($value['type_ids'])) {
                    $typeIds = explode(',', $value['type_ids'] ?? '');
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $value['type_name'] = implode(',', $types);
                }

                if (!empty($value['teacher'])) {
                    $value['teacher_name'] = $value['teacher']['username'];
                    unset($value['teacher']);
                }
            }
            unset($value);
        }
        return app('json')->success($coursewares);
    }


    public function down_cert(Request $request)
    {
        $planId = input('plan_id', 0);

        set_time_limit(0);
        $list = PlanStaff::field('complete_img_url as url,concat(username,idcard) as name')
            ->withJoin('staff')
            ->where('plan_id', $planId)
            ->where('progress', '100')
            ->where('complete_status', 10)
            ->where('complete_img_url', '<>', '')
            ->where('plan_staff.status', 1)
            ->select()->toArray();

        $zip = new \app\services\face\ZipService();
        $name = \app\model\plan\Plan::getOneName($planId, 'plan_name');
        $ret = $zip->createData($list);
        if ($ret == false) {
            return app('json')->fail($zip->getError());
        }
        return app('json')->success([
            'url' => $request->domain() . '/' . $zip->getZipUrl(),
        ]);
    }
}
